package com.focusai.efairy.utils;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.focusai.efairy.ui.base.BaseFragmentActivity;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;

import java.io.File;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/8/17.
 */

public class PictureUtil {

    // 拍照
    public static void openCameraCapture(final Activity activity, final int captureRequestCode, final File file) {
        // 先检查是否有sd卡
        if (!chekSDCardExist()) {
            return;
        }
        ((BaseFragmentActivity)activity).checkPermission(PermissionUtil.PERMISSION_CAMERA, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedList) {
                Intent intent = getPicFromCapture(activity, file);
                try {
                    activity.startActivityForResult(intent, captureRequestCode);
                } catch (Exception e) {
                    //忽略不支持android.media.action.IMAGE_CAPTURE 的处理
                }
            }

            @Override
            public void onFailed(int requestCode, List<String> deniedList) {

            }
        }, Manifest.permission.CAMERA);
    }

    // 拍照
    public static Intent getPicFromCapture(Context ct, File out) {
        // TODO Auto-generated method stub
        if (chekSDCardExist()) {
            Uri imageUri;
            imageUri = UriUtil.fromFile(out);
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra("return-data", false);//由于部分机子点击确定无反应，加次解决
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            return intent;
        }
        return null;
    }

    /*
     * 裁剪图片
     */
    public static Intent cameraCrop(Context context, File file, Uri uri, boolean takephoto) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");// 设置要裁剪的图片
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        if (!(Build.BRAND.equalsIgnoreCase("Meizu") || Build.BRAND.equalsIgnoreCase("Coolpad"))) {
            intent.putExtra("outputX", 640);
            intent.putExtra("outputY", 640);
        }
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        Uri imageUri = UriUtil.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.setClipData(ClipData.newRawUri(null, imageUri));
        }
        intent.putExtra("outputFormat", "JPEG");// 返回格式
        return intent;
    }
    // 获取图片
    public static Intent getPicFromSDCard(Context ct) {
        if (chekSDCardExist()) {
            Intent intentPhoto = new Intent(Intent.ACTION_PICK);
            intentPhoto.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intentPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            return intentPhoto;
        }
        return null;
    }

    /**
     * 检查SD卡是否存在
     * @return
     */
    public static boolean chekSDCardExist() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    //旧的方式
    public static String getPhotoPath(Context context, Uri selectedImage) {
        if (selectedImage != null) {
            String uriStr = selectedImage.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                return null;
            }
        }
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }

    //新的方式
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPhotoPathKitKat(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            } else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
